#pragma once

#include <iostream>
#include <string>
#include <unistd.h>
#include "sys/epoll.h"

namespace cloud
{
    class epoller
    {
    public:
        epoller():_epfd(-1){}

        ~epoller()
        {
            if(_epfd != -1) close(_epfd);
        }

        void Close()
        {
            if(_epfd != -1) close(_epfd);
        }

        void Create()
        {
            _epfd = epoll_create(128);
            if(_epfd < 0)
            {
                perror("epoll_create fail");
            }
        }

        bool AddEvent(int fd, uint32_t events)
        {
            epoll_event e;
            e.events = events;
            e.data.fd = fd; //用户数据，epoll底层不对其进行修改，未来就绪返回会用到
            int n = epoll_ctl(_epfd, EPOLL_CTL_ADD, fd, &e);
            if(n < 0)
            {
                perror("epoll add event fail");
                return false;
            }
            return true;
        }

        bool ModEvent(int fd, uint32_t events)
        {
            epoll_event e;
            e.events = events;
            e.data.fd = fd;
            int n = epoll_ctl(_epfd, EPOLL_CTL_MOD, fd, &e);
            if(n < 0)
            {
                perror("epoll mod event fail");
                return false;
            }
            return true;
        }

        int DelEvent(int fd)
        {
            // epoll删除fd时，必须保证fd合法
            return epoll_ctl(_epfd, EPOLL_CTL_DEL, fd, nullptr);
        }

        int GetFd()
        {
            return _epfd;
        }
        
    private:
        int _epfd;
    };
}